/* eslint-disable no-unused-vars */
/**
 * @description: 机构树状结构组件
 * @author: Daniel
 * @update: 2022/1/11
 */
import React, { useEffect, useState } from 'react'
import { makeStyles } from '@material-ui/core/styles'
import TreeView from '@material-ui/lab/TreeView'
import ExpandMoreIcon from '@material-ui/icons/ExpandMore'
import ChevronRightIcon from '@material-ui/icons/ChevronRight'
import TreeItem from '@material-ui/lab/TreeItem'

// const data = {
//   id: 'root',
//   name: 'Parent',
//   children: [
//     {
//       id: '1',
//       name: 'Child - 1',
//     },
//     {
//       id: '3',
//       name: 'Child - 3',
//       children: [
//         {
//           id: '4',
//           name: 'Child - 4',
//         },
//       ],
//     },
//   ],
// }

const useStyles = makeStyles({
  root: {
    height: '100%',
    flexGrow: 1,
    maxWidth: 400,
    marginTop: '15px',
  },
})

export default function RecursiveTreeView({ datas = [], onChange = () => {} }) {
  const [data, setData] = useState([])
  const classes = useStyles()

  const renderTree = (nodes) => {
    if (nodes.id) {
      return (
        <TreeItem key={nodes.id} nodeId={nodes.id} label={nodes.label}>
          {Array.isArray(nodes.children) ? nodes.children.map((node) => renderTree(node)) : null}
        </TreeItem>
      )
    } else {
      return ''
    }
  }

  /**
   * @description: 初始数据
   */
  useEffect(() => {
    if (Array.isArray(datas) && datas.length > 1) {
      setData({
        id: 'root',
        label: '全部',
        children: datas,
      })
    } else if (Array.isArray(datas) && datas.length === 1) {
      setData(datas[0])
    }
  }, [datas])
  return (
    <TreeView
      className={classes.root}
      defaultCollapseIcon={<ExpandMoreIcon />}
      defaultExpanded={['100', '101', '102']}
      defaultExpandIcon={<ChevronRightIcon />}
      onNodeToggle={(v, list) => console.log('onRowClick', list)}
      onNodeSelect={onChange}
    >
      {renderTree(data)}
    </TreeView>
  )
}
